package com.mingqijia.gassafety.job.job.warnStrategy;

/**
 * @author zhangfei
 * @version 1.0.0
 * @ClassName ReportCreateJob.java
 * @Description TODO
 * @createTime 2023年12月15日
 */

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.util.StringUtil;
import com.mingqijia.gassafety.db.entity.*;
import com.mingqijia.gassafety.db.mapper.*;
import com.mingqijia.gassafety.shared.constant.Constants;
import com.mingqijia.gassafety.shared.constant.EquipmentType;
import com.mingqijia.gassafety.shared.constant.ReportTypeEnum;
import com.mingqijia.gassafety.shared.utils.DateFormatUtil;
import com.mingqijia.gassafety.shared.utils.RedisCacheExt;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zhangfei
 * @version 1.0.0
 * @ClassName RunningStrategyJob.java
 * @Description TODO
 * @createTime 2023年12月15日
 */
@Component
@Slf4j
public class ReportCreateJob {


    @Autowired
    RedisCacheExt redisUtil;

    @Autowired
    DtuMapper dtuMapper;

    @Autowired
    HistoryAlarmMapper historyAlarmMapper;

    @Autowired
    RunningStrategyReportMapper reportMapper;

    @Autowired
    AppealLogMapper appealLogMapper;

    @Autowired
    GssOfflineMapper gssOfflineMapper;

    @Autowired
    ConsumerDtuHistoryMapper dtuHistoryMapper;

    @Autowired
    WorkOrderHistoryMapper workOrderHistoryMapper;
    /**
     *  每月1号 0 0 0 1 * ?
     */
    @XxlJob("strategyReport")
//    @Scheduled(cron = "0 0/1 * * * ?")
    public ReturnT<String> strategyReport(String param) {
        XxlJobLogger.log("XXLJOB-strategyReport start..." );
        log.info("strategyReport--start--------");
        String key = Constants.EQUIPMENT_WARNING_REPORT;
        try {
            Boolean acquire = redisUtil.setIfAbsent(key, String.valueOf(System.currentTimeMillis()), Constants.TIME_OUT);//15分钟超时
            if (acquire) {
                try {
                    //获取所有设备(多条设备对应多个规则)
                    List<Map<String, Object>> dtuMaps = dtuMapper.equipmentAndConsumer(EquipmentType.HOME_GAS_DETECTOR.getCode(), null, 2);
                    execute(dtuMaps,param);
                    return ReturnT.SUCCESS;
                } catch (Exception e) {
                    log.info("strategyReport-error:{}", e);
                } finally {
                    redisUtil.del(key);
                }
            }
        } catch (Exception e) {
            log.info("strategyReport-error:{}", e);
        }
        log.info("strategyReport--end--------");
        XxlJobLogger.log("XXLJOB-strategyReport end..." );
        return ReturnT.SUCCESS;
    }

    private boolean execute(List<Map<String, Object>> dtuMaps,String param) {
        log.info("strategyReport-execute：{}", JSONObject.toJSONString(dtuMaps));
        Date date = new Date();
        String format = StringUtil.isEmpty(param)?DateUtil.format(date, "yyyy-MM"):param;
        format=format+"-01";
        Date startDate= DateUtil.offsetMonth(DateUtil.parse(format),-1);
        Date endDate= DateUtil.parse(format+" 00:00:00");
        log.info("strategyReport-startDate：{}，endDate：{}", startDate,endDate);
        if (!CollectionUtil.isEmpty(dtuMaps)) {
            for (Map<String, Object> dtuMap : dtuMaps) {
                Object custType = dtuMap.get("cust_type");
                if (!"民用".equals(custType)){
                    continue;
                }
                Object iMEI = dtuMap.get("iMEI");
                Object spId = dtuMap.get("spId");
                Object consumerId = dtuMap.get("ConsumerId");
                RunningStrategyReport report = new RunningStrategyReport();
                report.setIMEI(iMEI+"");
                report.setSpId(spId+"");
                report.setConsumerId(Integer.parseInt(consumerId+""));
                LambdaQueryWrapper<WorkOrderHistory> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.or().eq(WorkOrderHistory::getIsDeleted,0).eq(WorkOrderHistory::getOrderType,1)
                        .eq(WorkOrderHistory::getDeviceId,iMEI)
                        .eq(WorkOrderHistory::getHandleStatus,1).orderByDesc(WorkOrderHistory::getCompleteTime);
                List<WorkOrderHistory> workOrderHistories = workOrderHistoryMapper.selectList(queryWrapper);
                log.info("strategyReport-workOrderHistories：{}", JSONObject.toJSONString(workOrderHistories));
                Date completeTime=startDate;
                if (!CollectionUtils.isEmpty(workOrderHistories)){
                     completeTime = workOrderHistories.get(0).getCompleteTime();
                }else {
                    LambdaQueryWrapper<ConsumerDtuHistory> wrapper = new LambdaQueryWrapper<>();
                    wrapper.or().eq(ConsumerDtuHistory::getIsDeleted,0).eq(ConsumerDtuHistory::getEvent,1)
                            .eq(ConsumerDtuHistory::getIMEI,iMEI).eq(ConsumerDtuHistory::getConsumerId,consumerId)
                            .orderByDesc(ConsumerDtuHistory::getCreatedAt);
                    List<ConsumerDtuHistory> consumerDtuHistories = dtuHistoryMapper.selectList(wrapper);
                    log.info("strategyReport-consumerDtuHistories：{}", JSONObject.toJSONString(consumerDtuHistories));
                    if (!CollectionUtils.isEmpty(consumerDtuHistories)){
                        ConsumerDtuHistory consumerDtuHistory = consumerDtuHistories.get(0);
                        completeTime = consumerDtuHistory.getCreatedAt();
                    }
                }
                List<String> days = DateFormatUtil.getDays(DateUtil.format(completeTime, "yyyy-MM-dd"), format, "yyyy-MM-dd", 1, new ArrayList<>());
                report.setDays(days.size()==0?0:days.size()-1);
                report.setReportDate(StringUtil.isEmpty(param)?DateUtil.format(DateUtil.offsetMonth(date,-1),"yyyy-MM"): DateUtil.format(startDate,"yyyy-MM"));
                //计算周期内内容
                LambdaQueryWrapper<HistoryAlarm> wrapper = new LambdaQueryWrapper<>();
                wrapper.or().eq(HistoryAlarm::getIsDeleted,0)
                        .eq(HistoryAlarm::getSpId,spId)
                        .eq(HistoryAlarm::getIMEI,iMEI)
                        .between(HistoryAlarm::getCreatedAt,startDate,endDate)
                        .orderByAsc(HistoryAlarm::getCreatedAt);
                List<HistoryAlarm> historyAlarms = historyAlarmMapper.selectList(wrapper);
                if (!CollectionUtils.isEmpty(historyAlarms)){
                    List<Long> alarms = historyAlarms.stream().map(HistoryAlarm::getId).collect(Collectors.toList());
                    List<AppealLog> appealLogs = appealLogMapper.selectAppealDetail(alarms,0);
                    if (CollectionUtils.isEmpty(appealLogs)){
                        report.setAlarmIds(JSONObject.toJSONString(alarms));
                        report.setUndisposedNumber(alarms.size());
                        report.setAlarmNumber(alarms.size());
                    }else {
                        List<Long> collect = appealLogs.stream().map(AppealLog::getAlarmBrokenId).collect(Collectors.toList());
                        List<AppealLog> appealDetail = appealLogMapper.selectAppealDetail(alarms,1);
                        report.setUndisposedNumber(appealDetail.size());
                        report.setAlarmIds(JSONObject.toJSONString(collect));
                        report.setAlarmNumber(collect.size());
                    }
                }else {
                    report.setAlarmIds("[]");
                }
                LambdaQueryWrapper<GssOffline> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(GssOffline::getIMEI,iMEI)
                        .between(GssOffline::getDate,DateUtil.format(startDate,"yyyy-MM-dd")
                                ,DateUtil.offsetDay(endDate,-1));
                List<GssOffline> gssOfflines = gssOfflineMapper.selectList(lambdaQueryWrapper);
                log.info("gssOfflines:{}",JSONObject.toJSONString(gssOfflines));
                if (!CollectionUtils.isEmpty(gssOfflines)){
                    BigDecimal sumTime=new BigDecimal("0");
                    for (GssOffline gssOffline : gssOfflines) {
                        String duration = gssOffline.getDuration();
                        BigDecimal bigDecimal = new BigDecimal(0);
                        if(duration.contains("时")&&duration.contains("分")){
                            String[] split = duration.split("时");
                            String hour=split[0];
                            String minute=split[1].split("分")[0];
                            if (minute.length()==1)minute="0"+minute;
                            bigDecimal=new BigDecimal(hour+"."+minute);
                        }
                        sumTime=  sumTime.add(bigDecimal);
                    }
                    String offlineTime="";
                    if (sumTime.toString().contains(".")) {
                        String string = sumTime.toString();
                        String[] split =string.split("\\.");
                        String minute="0";
                        int i=0;
                        if (Integer.parseInt(split[1])>=60) {
                            minute=String.valueOf(Integer.parseInt(split[1])-60);
                            log.info("offlineTime-minute:{}",minute);
                            i=i+1;
                        }else {
                            minute =split[1];
                        }
                        offlineTime=Integer.parseInt(split[0])+i+"时"+minute+"分";
                    }else {
                        offlineTime="0时0分";
                    }
                    report.setOfflineTime(offlineTime);
                }
                int statusAlarm=0;
                int statusOffline=0;
                if (report.getAlarmNumber()!=null&&report.getAlarmNumber()!=0){
                    statusAlarm=report.getUndisposedNumber()!=0?2:1;
                }
                if (report!=null&&report.getOfflineTime()!=null&&
                                 !"0".equals(report.getOfflineTime())){
                    statusOffline=1;
                }
                report.setStatus(ReportTypeEnum.getPushTypes(statusAlarm,statusOffline).getStatus());
                reportMapper.insert(report);
            }
        }
        return false;
    }


}